<?php
	require_once('_inc.php');

	$db	= D::$user->db();

	$units	= include( D::$user->path().'/units.php' );
	//print_r($units);die;



	if( $_GET['act'] === 'upload' ){
		include('stuff_upload.php');
		die;
	}

	if( $_GET['act'] === 'list'){

		file_put_contents('log.txt', var_export($_POST, 1));

		$dir	= $_POST['dir'] == 'DESC' ? 'DESC' : 'ASC';
		if( in_array($_POST['sort'], array('原料分类','动物种类','饲料名','中国饲料号')) ){
			$sort	= $_POST['sort'] .' ' . $dir. ',id ASC';
		}else{
			$sort	= 'id '.$dir;
		}
		
		$filter	= json_decode($_POST['filter']);

		if( !empty($filter) ){
			$tj	= array();
			foreach($filter as $key=>$val){
				$val	= (int) $val;
				if( $val > 0 && in_array($key, array('原料分类','动物种类','饲料名','中国饲料号')) ){
					$tj[]	= $key . '=' . $val;
				}
			}
			$tj	= empty($tj) ? 1 : join(' AND ', $tj);
		}else{
			$tj	= 1;
		}

		$C		= $db->one('SELECT count(id) FROM stuff WHERE '.$tj);

		$start		= (int) $_POST['start'];
		$limit		= (int) $_POST['limit'];

		if( $limit <1 || $limit > 40 ){
				$limit	= 20;
		}

		if( $start >= $C['count(id)'] ){
			$start = 0;
		}

		$L		= array();
		$L['root']	= $db->all('SELECT id,原料分类,动物种类,饲料名,中国饲料号,描述 FROM stuff WHERE '.$tj.' ORDER BY '.$sort.' limit ' .$start .','.$limit);

		$L['Total']	= $C['count(id)'];
		echo json_encode($L);
		die;
	}

	if( $_GET['act'] === 'load'){		
		$id	= (int) $_POST['id'];
		$L	= $db->one("SELECT * FROM stuff WHERE id=" .$id );
		$A	= @unserialize($L['sArray']); unset($L['sArray']);
		foreach($A as $k=>$v){
			if( !empty($v) ){
				$L['sArray_'.$k]	= $v;
			}
		}
		echo json_encode($L); 
		die;
	}

	if( $_GET['act'] === 'save'){
		$return	= array('success'=>true);
		$id	= (int) $_POST['id'];
		$_POST['sArray']	= saveArray();
		if($id){
			$db->update('stuff', '原料分类,动物种类,饲料名,中国饲料号,单价,配比上限,配比下限,干物质,库存,描述,备注,sArray', 'id='. $id);
		}else{
			$db->insert('stuff', '原料分类,动物种类,饲料名,中国饲料号,单价,配比上限,配比下限,干物质,库存,描述,备注,sArray');
		}
		echo json_encode($return);
		update($db);
		die;
	}



	if( $_GET['act'] === 'del'){
		if( preg_match_all("/\d+/", $_POST['dels'], $dels) ){
			$dels	= $dels[0];
			$sql	= "DELETE FROM stuff WHERE id=" .join(' OR id=', $dels);
			$db->query($sql);
		}
		update($db);
		die('ok');
	}



	$tpl	= D::$user->tpl();
	$tpl->load('units', 'poultry', 'stuff_group');	
	$tpl->assign('units_list', $units);
	$tpl->display();

	function update(&$db){
		$path	= D::$user->path();
	}

	function saveArray(){
		global $units;
		$R	= array();
		foreach($units as $k=>$v){
			$k2	= 'sArray_'.$k;
			if( !empty($_POST[$k2]) ){
				$R[$k]	= $_POST[$k2];
			}
			unset($_POST[$k2]);
		}
		return serialize($R);
	}
?>
